﻿using System;
using System.Reflection;

namespace SimpleOrmCFPC.upgrade
{
    public interface PrimaryKeyComputer
    {
        bool IsPrimaryKey(PropertyInfo property);
    }

    public class ColumnMappingFactory : IColumnMappingFactory
    {
        private Func<PropertyInfo, DbType> dbTypeConverter;

        public ColumnMappingFactory(Func<PropertyInfo, DbType> dbTypeConverter)
        {
            this.dbTypeConverter = dbTypeConverter;
        }

        public ColumnMapping Create(PropertyInfo property)
        {
            return new ColumnMapping(property.Name, IsPk(property), IsNotNull(property),
                           IsAutoInc(property),dbTypeConverter(property), GetMaxLength(property)
                       );
        }

        private static bool IsPk(PropertyInfo p)
        {
            return p.GetCustomAttributes(typeof(PrimaryKeyAttribute), true).Length > 0;
        }

        private static bool IsAutoInc(PropertyInfo p)
        {
            return p.GetCustomAttributes(typeof(AutoIncrementAttribute), true).Length > 0;
        }

        private static bool IsNotNull(PropertyInfo p)
        {
            return p.GetCustomAttributes(typeof(NotNullAttribute), true).Length > 0;
        }

        private static int GetMaxLength(PropertyInfo property)
        {
            object[] attrs = property.GetCustomAttributes(typeof(MaxLengthAttribute), true);
            return attrs.Length > 0 ? ((MaxLengthAttribute)attrs[0]).Length : 255;
        }
    }
}